#include <iostream>
#include <cerrno>
#include <unistd.h>
#include <string>
#include <cstring>
#include <pthread.h>
#define NUM 5
using namespace std;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond;
//子线程执行的任务
void* active(void* args)
{
   string name = static_cast<const char*> (args);
   while(true)
   {
      pthread_mutex_lock(&mutex); //加锁
      pthread_cond_wait(&cond,&mutex);  //等待主线程的信号
      cout<<name<<"活动"<<endl;
      pthread_mutex_unlock(&mutex); //解锁
   }
   return nullptr;
}
//主线程
int main()
{
    pthread_cond_init(&cond,nullptr);  //条件变量初始化
    //1.创建一批子线程
    pthread_t td[NUM]; 
    for(int i = 0;i < NUM;i++)
    {
        char* name = new char[64];
        snprintf(name,64,"thread-%d",i+1);
        pthread_create(td+i,nullptr,active,name);
    }

    sleep(3);
    //主线程开始唤醒子线程
    while(true)
    {
      cout<<"main thread wakeup thread..."<<endl;
      //pthread_cond_signal(&cond);  //一次唤醒一个线程
      pthread_cond_broadcast(&cond);  //一次唤醒整个线程
      sleep(1);
    }

    //?.线程等待
    for(int i = 0;i < NUM;i++)
    {
        int n = pthread_join(td[i],nullptr);
        if(n != 0)
        {
           cerr<<"error join："<<n<<strerror(n)<<endl;
        }
    }
    return 0;
}